package com.coursebooking.controller;

import com.baomidou.mybatisplus.annotation.TableField;
import com.coursebooking.model.Student;
import com.coursebooking.model.User;
import com.coursebooking.service.StudentService;
import com.coursebooking.service.UserService;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/students")
@CrossOrigin(origins = "*")
public class StudentController {

    @Autowired
    private StudentService studentService;
    @Autowired
    private UserService userService;

    @GetMapping
    @PreAuthorize("hasRole('ADMIN') or hasRole('TEACHER')")
    public ResponseEntity<List<Student>> getAllStudents() {
        List<Student> students = studentService.findAll();
        return ResponseEntity.ok(students);
    }

    @GetMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or hasRole('TEACHER') or hasRole('STUDENT')")
    public ResponseEntity<Student> getStudentById(@PathVariable Long id) {
        Optional<Student> student = studentService.findById(id);
        return student.map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> createStudent(@RequestBody StudentRequest studentRequest) {
        try {
            if (studentService.existsByStudentId(studentRequest.getStudentId())) {
                return ResponseEntity.badRequest().body(new MessageResponse("学号已存在"));
            }

            if (studentService.existsByEmail(studentRequest.getEmail())) {
                return ResponseEntity.badRequest().body(new MessageResponse("邮箱已存在"));
            }
            if (studentRequest.getUsername() == null || studentRequest.getUsername().isEmpty()){
                return ResponseEntity.badRequest().body(new MessageResponse("用户名不能为空"));
            }
            if (studentRequest.getPassword() == null || studentRequest.getPassword().isEmpty()){
                return ResponseEntity.badRequest().body(new MessageResponse("密码不能为空"));
            }
            if(userService.existsByUsername(studentRequest.getUsername())){
                return ResponseEntity.badRequest().body(new MessageResponse("用户名已存在"));
            }
            Student student = new Student();
            BeanUtils.copyProperties(studentRequest, student);
            Student entity =  studentService.createStudent(student);
            userService.createUser(studentRequest.getUsername(), studentRequest.getPassword(), studentRequest.getEmail(), User.Role.STUDENT,student.getId());

            return ResponseEntity.ok(entity);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new MessageResponse("创建学生失败: " + e.getMessage()));
        }
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN') or hasRole('STUDENT')")
    public ResponseEntity<?> updateStudent(@PathVariable Long id, @RequestBody Student student) {
        try {
            if (!studentService.existsById(id)) {
                return ResponseEntity.notFound().build();
            }
            student.setId(id);
            Student entity = studentService.updateStudent(student);

            return ResponseEntity.ok(entity);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new MessageResponse("更新学生信息失败: " + e.getMessage()));
        }
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> deleteStudent(@PathVariable Long id) {
        try {
            studentService.deleteStudent(id);
            return ResponseEntity.ok(new MessageResponse("学生删除成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new MessageResponse("删除学生失败: " + e.getMessage()));
        }
    }

    @GetMapping("/student-id/{studentId}")
    @PreAuthorize("hasRole('ADMIN') or hasRole('TEACHER')")
    public ResponseEntity<Student> getStudentByStudentId(@PathVariable String studentId) {
        Optional<Student> student = studentService.findByStudentId(studentId);
        return student.map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
    }

    @GetMapping("/email/{email}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Student> getStudentByEmail(@PathVariable String email) {
        Optional<Student> student = studentService.findByEmail(email);
        return student.map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
    }

    @GetMapping("/check/student-id/{studentId}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ExistsResponse> checkStudentIdExists(@PathVariable String studentId) {
        boolean exists = studentService.existsByStudentId(studentId);
        return ResponseEntity.ok(new ExistsResponse(exists));
    }

    @GetMapping("/check/email/{email}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ExistsResponse> checkEmailExists(@PathVariable String email) {
        boolean exists = studentService.existsByEmail(email);
        return ResponseEntity.ok(new ExistsResponse(exists));
    }

    // 内部类定义
    public static class StudentRequest {
        private String name;
        private String studentId;
        private String email;
        private String phone;
        private String grade;
        private String username;
        private String password;
        // 新增字段
        private Student.GenderEnum gender; // ENUM: 'MALE', 'FEMALE'
        private String major; // VARCHAR

        private String className; // 班级

        private Integer enrollmentYear; // 入学年份

        @JsonFormat(pattern = "yyyy-MM-dd")
        private Date birthDate; // 出生日期

        public Student.GenderEnum getGender() {
            return gender;
        }

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public void setGender(Student.GenderEnum gender) {
            this.gender = gender;
        }

        public String getMajor() {
            return major;
        }

        public void setMajor(String major) {
            this.major = major;
        }

        public String getClassName() {
            return className;
        }

        public void setClassName(String className) {
            this.className = className;
        }

        public Integer getEnrollmentYear() {
            return enrollmentYear;
        }

        public void setEnrollmentYear(Integer enrollmentYear) {
            this.enrollmentYear = enrollmentYear;
        }

        public Date getBirthDate() {
            return birthDate;
        }

        public void setBirthDate(Date birthDate) {
            this.birthDate = birthDate;
        }

        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }

        private String address; // 地址
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        public String getStudentId() { return studentId; }
        public void setStudentId(String studentId) { this.studentId = studentId; }
        public String getEmail() { return email; }
        public void setEmail(String email) { this.email = email; }
        public String getPhone() { return phone; }
        public void setPhone(String phone) { this.phone = phone; }
        public String getGrade() { return grade; }
        public void setGrade(String grade) { this.grade = grade; }
    }

    public static class MessageResponse {
        private String message;

        public MessageResponse(String message) {
            this.message = message;
        }

        public String getMessage() { return message; }
        public void setMessage(String message) { this.message = message; }
    }

    public static class ExistsResponse {
        private boolean exists;

        public ExistsResponse(boolean exists) {
            this.exists = exists;
        }

        public boolean isExists() { return exists; }
        public void setExists(boolean exists) { this.exists = exists; }
    }
}